<template>
  <div>
    <el-form ref="myform" :model="formItem" label-width="120px" size="mini" class="form-view">
      <el-row :gutter="40">
        <el-col :span="12">
          <el-form-item label="名称">
            {{ formItem.title }}
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="关键字">
            {{ formItem.keywords }}
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="附件">
            <div v-for="fileObj in formItem.attachment" :key="fileObj.fsId">
              <el-link type="primary" :href="downloadFileUrl(fileObj.fsId)" :download="downloadFileUrl(fileObj.fsId)" target="_blank">{{ fileObj.name }}</el-link>
            </div>
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="">
            <Tinymce ref="tinymce" v-model="formItem.content" :height="300" menubar="false" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script>
import Tinymce from '@neu/biz-core/components/Tinymce'
// import MarkdownEditor from '@neu/biz-core/components/MarkdownEditor'
import treeselect from '@neu/biz-core/components/TreeSelect'
import { detail, downloadFileUrl, updateVolume } from '@neu/dcom-ui/api/servicelevel'
import { tree } from '@neu/dcom-ui/api/knowledgeType'
import { clone } from '@neu/biz-core/utils/utils'
import { deepClone } from '@neu/biz-core/utils'

// 定义一个表单原始项
const formItem = {
  /** 标题 */
  title: '',
  /** 内容 */
  content: '',
  // 附件列表
  attachment: [],
  // 关键字
  keywords: '',
  // 关键字名称列表
  // keywordsName: [],
  // 阅读量
  // readingVolume: '',
  // 创建人编码
  usercode: '',
  // 创建人名称
  username: '',
  // 评论
  comment: []
}
export default {
  name: 'ServiceLevelViewPage',
  components: {
    treeselect,
    // quillEditor
    // MarkdownEditor
    Tinymce
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      content: null,
      editorOption: {},
      // 编辑的表单内容
      formItem: clone(formItem),
      test: '',
      downloadFileUrl: downloadFileUrl
    }
  },
  mounted() {
    updateVolume(this.id)
  },
  watch: {
    // 监控id的变化，初始化表单数据
    id: {
      handler() {
        if (this.id) {
          this.fetch()
        }
      },
      immediate: true
    }
  },
  methods: {
    // 初始化表单数据
    fetch() {
      if (this.id !== -1) {
        detail(this.id).then(response => {
          const data = response.data
          if (data.attachment) {
            const fileJoins = data.attachment.split('||')
            data.attachment = fileJoins.map(it => {
              const fsInfo = it.split('@@')
              return {
                fsId: fsInfo[0],
                name: fsInfo[1]
              }
            })
          } else {
            data.attachment = []
          }
          this.formItem = {
            ...data
          }
        })
      } else {
        this.formItem = clone(formItem)
      }
    },
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      const updated = this.id !== -1
      return new Promise(resolve => {
        this.$refs.editForm.validate((valid) => {
          if (valid) {
            const deepCloneForm = deepClone(this.formItem)
            // 将附件转为字符串存储
            if (deepCloneForm.attachment.length > 0) {
              deepCloneForm.attachment = deepCloneForm.attachment.map(it => it.fsId + '@@' + it.name).join('||')
            } else {
              deepCloneForm.attachment = ''
            }

            if (deepCloneForm.keywords) {
              deepCloneForm.keywords = deepCloneForm.keywords.join(' ')
            } else {
              data.keywords = ''
            }

            if (updated) {
              resolve(update(this.id, deepCloneForm))
            } else {
              resolve(create(deepCloneForm))
            }
          } else {
            resolve(false)
          }
        })
      })
    },
    reset() {
      this.$refs.editForm.resetFields()
      this.formItem = clone(this.formItem)
    },

    handleSuccess(response, file, fileList) {
      if (response.status === 'failure') {
        this.$message({
          showClose: true,
          message: response.data,
          type: 'error'
        })
      } else {
        this.$message({
          showClose: true,
          message: '文件上传成功',
          type: 'success'
        })
        const obj = {
          fsId: response.data.fsId,
          name: response.data.name
        }
        const fsIdArr = this.formItem.attachment.map(t => t.fsId)
        if (!fsIdArr.includes(obj.fsId)) {
          this.formItem.attachment.push(obj)
        } else {
          fileList.pop()
        }
      }
    },
    handleError(err, file, fileList) {
      console.log(err)
    },
    /** 文件移除 */
    handleRemove(file, fileList) {
      this.formItem.attachment.splice(this.formItem.attachment.indexOf(file), 1)
    },
    /** 删除某一项 */
    removeUser(tag) {
      this.formItem.keywords = this.formItem.keywords.filter(t => {
        return t.name !== tag.name
      })
    },
    /** 删除所有项 */
    clearAllUser() {
      this.formItem.keywords = []
    },
    add(value) {
      const keywordsName = this.formItem.keywords
      if (!keywordsName.includes(value)) {
        this.formItem.keywords.push(value)
        this.test = ''
      }
      console.log(value)
    }
  }
}
</script>

